<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 13:59
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder; // 引入ZBuilder
use app\common\model\Vote as VoteModel;
use think\Db;

class Vote extends Admin
{
    //投票列表
    public function vote_list()
    {
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = VoteModel::where($map)->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '投票编辑',
            'icon'  => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('edit', ['id' => '__id__']),
        ];
        $btn_access = [
            'title' => '新增投票',
            'icon'  => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href'  => url('add'),
        ];
        $btn_access2 = [
            'title' => '删除投票',
            'icon'  => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('delete', ['id' => '__id__']),
        ];
        $btn_access3 = [
            'title' => '投票统计',
            'icon'  => 'fa fa-fw fa-bar-chart-o',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('detail', ['id' => '__id__']),
        ];
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('title', '投票标题', 'text.edit')
            ->addColumn('desc', '投票说明', 'text')
            ->addColumn('user_num', '投票人数', 'text')
            ->addColumn('start_time', '开始日期', 'datetime','','Y-m-d H:i:s')
            ->addColumn('end_time', '结束日期', 'datetime','','Y-m-d H:i:s')
            ->addColumn('created_time', '创建日期', 'datetime','','Y-m-d H:i:s')
            ->addColumn('right_button','操作','btn')
            ->setColumnWidth([
                'id'  => 50,
                'title' => 200,
                'user_num' => 50,
                'desc' => 250,
                'start_time'=> 130,
                'end_time'=> 130,
                'created_time'=> 130,
                'right_button'=>100
            ])
            ->setTableName('qt_notic') // 指定数据表名
            ->addTopButton('custom',$btn_access) // 添加顶部按钮
            ->addRightButton('edit',$btn_access1) // 添加右侧按钮
            ->addRightButton('delete',$btn_access2) // 添加右侧按钮
            ->addRightButton('detail',$btn_access3) // 添加右侧按钮
            ->addOrder('id,title,create_time,update_time')
            ->setPrimaryKey('id') // 设置主键名为username
            ->setPageTitle('投票列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }
    //添加投票
    public function add(){
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            //var_dump($data);die;
            $result = $this->validate($data, 'Vote.add');
            if(true !== $result) $this->error($result);
            $data['start_time'] = strtotime( $data['start_time']);
            $data['end_time'] = strtotime( $data['end_time']);
            $data['created_time'] = time();
            $insert = VoteModel::create($data);
            if(!empty($data['choice'])){
                //删除投票选项并创建新的投票选项
                $choiceData = explode("\n",$data['choice']);
                $inserData = [];
                foreach ($choiceData as $key=>$value){
                    $inserData[$key]['vote_id'] = $insert->id;
                    $inserData[$key]['title'] = $value;
                }
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_vote_choice')->insertAll($inserData);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->error('选项编辑失败');
                }
            }

            if ($insert) {
                $this->success('新增成功', 'vote_list');
            } else {
                $this->error('新增失败');
            }
        }else
        {
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['text:7','title','投票标题'],
                        ['text:7','desc','投票描述'],
                        ['Ueditor:7','content','投票详情'],
                        ['datetime:7','start_time', '开始时间',''],
                        ['datetime:7','end_time', '结束时间',''],
                        ['radio', 'type', '类型', '', [1=>'单选', 2=>'多选'],'1'],
                        ['textarea:7', 'choice', '选项','<code>每一行为一个选项</code>'],
                        ['radio', 'status', '状态', '', [1=>'显示', 2=>'隐藏'],'1'],
                        ['radio', 'people_type', '投票人类型', '', [1=>'匿名投票', 2=>'实名投票'],'1'],
                        ['text:7','sort','排序','<code>值越小越靠前,1-100</code>','50'],
                    ]
                )
                ->setPageTitle('添加投票')
                ->fetch();
        }
    }

    //编辑投票
    public function edit($id=null){
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Vote.add');
            if(true !== $result) $this->error($result);
            $data['start_time'] = strtotime( $data['start_time']);
            $data['end_time'] = strtotime( $data['end_time']);
            if(!empty($data['choice'])){
                //删除投票选项并创建新的投票选项
                $choiceData = explode("\n",$data['choice']);
                $inserData = [];
                foreach ($choiceData as $key=>$value){
                    $inserData[$key]['vote_id'] = $id;
                    $inserData[$key]['title'] = $value;
                }
                $find = Db::name('qt_vote_log')->where('vote_id',$id)->find();
                if($find){
                    $this->error('已有投票的不允许修改');
                }
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_vote_choice')->where('vote_id',$id)->delete();
                    Db::name('qt_vote_choice')->insertAll($inserData);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->error('选项编辑失败');
                }
            }
            if (VoteModel::update($data)) {
                $this->success('编辑成功', 'vote_list');
            } else {
                $this->error('编辑失败');
            }
        }else
        {
            $info = VoteModel::get($id);
            $choice = Db::name('qt_vote_choice')->where('vote_id',$id)->column('title');
            $info['choice'] = implode("\n",$choice);
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id','id'],
                        ['text:7','title','投票标题'],
                        ['text:7','desc','投票描述'],
                        ['Ueditor:7','content','投票详情'],
                        ['datetime:7','start_time', '开始时间',''],
                        ['datetime:7','end_time', '结束时间',''],
                        ['radio', 'type', '类型', '', [1=>'单选', 2=>'多选']],
                        ['textarea:7', 'choice', '选项','<code>每一行为一个选项</code>'],
                        ['radio', 'status', '状态', '', [1=>'显示', 2=>'隐藏']],
                        ['radio', 'people_type', '投票人类型', '', [1=>'匿名投票', 2=>'实名投票']],
                        ['text:7','sort','排序','<code>值越小越靠前,1-100</code>'],
                    ]
                )
                ->setFormData($info)
                ->setPageTitle('编辑公告')
                ->fetch();
        }
    }
    //删除投票
    public function delete($id=null){
        if ($id === null) $this->error('缺少参数');
        $find = Db::name('qt_vote_log')->where('vote_id',$id)->find();
        if($find){
            $this->error('已有投票的不允许删除');
        }
        try{
            Db::startTrans();
            //修改订单状态
            Db::name('qt_vote')->where('id',$id)->delete();
            Db::name('qt_vote_choice')->where('vote_id',$id)->delete();
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $this->error('系统繁忙请稍后再试','vote_list');
        }
        $this->success('删除成功','vote_list');

    }

    /**
     * 投票统计
     */
    public function detail($id){
        //查找所有的投票选项
        $choiceRes = Db::name('qt_vote_choice')->field('id,title')->where('vote_id',$id)->select();
        //dump($choiceRes);die;
        //总的投票数
        $totalVote = Db::name('qt_vote_log')->where('vote_id',$id)->count();
        foreach ($choiceRes as $key=>$value){
            $choiceRes[$key]['title']  = str_replace(array("\r\n", "\r", "\n"), "", $value['title']);
            //单个投票数
            $choiceCount = Db::name('qt_vote_log')->where('vote_id',$id)->where('vote_choice_id',$value['id'])->count();
            $choiceRes[$key]['count'] = $choiceCount;
            //单个投票比例
            if($totalVote == '0'){
                $choiceRes[$key]['percentage'] = '0';
            }else{
                $percentage = $choiceCount / $totalVote;
                $bili = sprintf("%.2f",$percentage);
                $choiceRes[$key]['percentage'] = ($bili * 100).'%';
            }

        }
        $data = Db::name('qt_vote')->where('id',$id)->find();
        $data['total'] = $totalVote;//总投票人数
        $data['choice'] = $choiceRes;//选择数据
        $data['start_time']=date('Y-m-d H:i:s',$data['start_time']);
        $data['end_time']=date('Y-m-d H:i:s',$data['end_time']);
        $data['created_time']=date('Y-m-d H:i:s',$data['created_time']);
        $table_head = [
            ['ID', '选项', '投票数','投票比例']
        ];
        if($data['people_type'] == '1'){
            $data['people_type'] = '匿名投票';
        }
        if($data['people_type'] == '2'){
            $data['people_type'] = '实名投票';
        }
        return ZBuilder::make('form')
            ->setPageTitle('投票详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['static:8','title','投票名称'],
                ['static:8','desc','投票描述'],
                ['ueditor:9','content','投票详情'],
                ['static:4','created_time','创建时间'],
                ['static:4','start_time','开始时间'],
                ['static:4','end_time','结束时间'],
                ['static:4','people_type','投票方式'],
                ['static:4','total','投票数'],
                ['complexTable:12', 'list_user', '投票选项', $data['choice'],$table_head]
            ])
            ->hideBtn(['submit'])
            ->setFormData($data)
            ->fetch();

    }



}